package com.defysoft.waukids.album;

import java.util.ArrayList;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.Custom_Data_Type.AlbumDetailLoad;
import com.defysoft.waukids.Custom_Data_Type.Album_Main_Photo;
import com.defysoft.waukids.Data_Sharedpreferences;
import com.defysoft.waukids.JsonParser;
import com.defysoft.waukids.PublicConstant;
import com.defysoft.waukids.PublicSharedpreferences;
import com.defysoft.waukids.R;
import com.defysoft.waukids.Sqlite_Connect;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

public class Album_Detail_Edit extends BaseActivity{
	Toolbar toolbar;
	EditText et []  = new EditText[2];
	ImageView iv_img [] = new ImageView[10];
	FrameLayout fl [] = new FrameLayout[10];
	View btn_save ;
	LinearLayout ly,ly_1;
	String PK_Alb_Code="";
	AlbumDetailLoad albumDetailLoad;
	ArrayList<Album_Main_Photo> photoList;
	private ImageLoader imageLoader;
	DisplayImageOptions defaultOptions;
	PublicSharedpreferences psf;
	public Data_Sharedpreferences.SF_Member member;
	int photo_count;
	Sqlite_Connect sqlite_Connect;
	private final int SUCCESS = 10;
	private final int FAIL = 9;
	private final int NETWORK_ERR = 8;
	private final int EDIT_SUCCESS = 7;
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.album_detail_edit);
		setStartData();
		setStartToolbar();
		startNetwork(0);
		registerReceiver(mToastMessageReceiver, new IntentFilter(
				"com.defysoft.waukids.TOAST_MESSAGE"));
	}
	
	private void setStartToolbar() {
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}
	
	@Override
	public void setStartData() {
		super.setStartData();
		psf = new PublicSharedpreferences(this);
		psf.setMembersp();
		member = psf.getMembersp();
		sqlite_Connect = new Sqlite_Connect(this);
		PK_Alb_Code = getIntent().getStringExtra("PK_Alb_Code");
		et[0] = (EditText)findViewById(R.id.ALBUM_EDIT_TITLE);
		et[1] = (EditText)findViewById(R.id.ALBUM_EDIT_SUB);
		toolbar = (Toolbar) findViewById(R.id.ALBUM_EDIT_TOOLBAR);
		btn_save = (View)findViewById(R.id.ALBUM_EDIT_TOOLBAR_SAVE);
		
		btn_save.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				alertDialog();		
			}
		});
		
		ImageLayout();
		Init();
	}
	
	void mainThread(){
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
					"code=" + CODE_ALBUM_DETAIL_LOAD+ "&PK_Alb_Code="+PK_Alb_Code));
			if (jsonObject.getBoolean("success")) {
				albumDetailLoad = JsonParser.albumDetailLoad(jsonObject.getString("payload"));
				photoList = JsonParser.Album_Main_Photo_Parser(jsonObject.getString("photo"));
				photo_count = jsonObject.getInt("count");
				onNetworkCallback(SUCCESS, "");
			} else {
				onNetworkCallback(FAIL, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(NETWORK_ERR,e.toString()+" where mainThread()");
		}
	}
	
	void editThread(){
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
					"code=" + CODE_ALBUM_DETAIL_EDIT+ "&PK_Alb_Code="+PK_Alb_Code+"&subject="+et[1].getText().toString()+"&title="+et[0].getText().toString()));
			if (jsonObject.getBoolean("success")) {
				onNetworkCallback(EDIT_SUCCESS, jsonObject.getString("payload"));
			} else {
				onNetworkCallback(FAIL, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(NETWORK_ERR,  e.toString()+" where editThread()");
		}
	}
	@Override
	public void startThread(int choice) {
		super.startThread(choice);
		final int cho = choice;
		firstThread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				switch (cho) {
				case 0:
					mainThread();
					break;

				case 1:
					editThread();
					break;
				}		
			}
		});
		firstThread.start();
		startDIal();
	}
	
	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);
		switch (_message.what) {
		case SUCCESS:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			et[0].setText(albumDetailLoad.Alb_Name);
			et[1].setText(albumDetailLoad.Alb_Sub);
			imageSetting();
			break;
		case EDIT_SUCCESS:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
			.show();
			setResult(REFRESH_CODE);
			finish();
			break;
			
		case FAIL:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
					.show();
			break;
		
		case NETWORK_ERR:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			sqlite_Connect.insert_Err_Log((String)_message.obj,android.os.Build.VERSION.SDK_INT,"ALBUM_DETAIL_EDIT", member.Email);
			break;
		}
	}
	
	void ImageLayout(){
		//이미지 감싸고있는 뷰
		ly = (LinearLayout)findViewById  (R.id.ALBUM_EDIT_PHOTO_CONTAINER);
		ly_1=(LinearLayout)findViewById  (R.id.ALBUM_EDIT_PHOTO_CON_1);
		fl[0] = (FrameLayout)findViewById(R.id.ALBUM_EDIT_PHOTO_FRAME_1);
		fl[1] = (FrameLayout)findViewById(R.id.ALBUM_EDIT_PHOTO_FRAME_2);
		fl[2] = (FrameLayout)findViewById(R.id.ALBUM_EDIT_PHOTO_FRAME_3);
		fl[3] = (FrameLayout)findViewById(R.id.ALBUM_EDIT_PHOTO_FRAME_4);
		fl[4] = (FrameLayout)findViewById(R.id.ALBUM_EDIT_PHOTO_FRAME_5);
		fl[5] = (FrameLayout)findViewById(R.id.ALBUM_EDIT_PHOTO_FRAME_6);
		fl[6] = (FrameLayout)findViewById(R.id.ALBUM_EDIT_PHOTO_FRAME_7);
		fl[7] = (FrameLayout)findViewById(R.id.ALBUM_EDIT_PHOTO_FRAME_8);
		fl[8] = (FrameLayout)findViewById(R.id.ALBUM_EDIT_PHOTO_FRAME_9);
		fl[9] = (FrameLayout)findViewById(R.id.ALBUM_EDIT_PHOTO_FRAME_10);
		//사진 들어갈 이미지 뷰
		iv_img[0] = (ImageView)findViewById(R.id.ALBUM_EDIT_PHOTO_1);
		iv_img[1] = (ImageView)findViewById(R.id.ALBUM_EDIT_PHOTO_2);
		iv_img[2] = (ImageView)findViewById(R.id.ALBUM_EDIT_PHOTO_3);
		iv_img[3] = (ImageView)findViewById(R.id.ALBUM_EDIT_PHOTO_4);
		iv_img[4] = (ImageView)findViewById(R.id.ALBUM_EDIT_PHOTO_5);
		iv_img[5] = (ImageView)findViewById(R.id.ALBUM_EDIT_PHOTO_6);
		iv_img[6] = (ImageView)findViewById(R.id.ALBUM_EDIT_PHOTO_7);
		iv_img[7] = (ImageView)findViewById(R.id.ALBUM_EDIT_PHOTO_8);
		iv_img[8] = (ImageView)findViewById(R.id.ALBUM_EDIT_PHOTO_9);
		iv_img[9] = (ImageView)findViewById(R.id.ALBUM_EDIT_PHOTO_10);	
	}                                          
	                                           
	void imageSetting(){
		ly_1.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Toast.makeText(Album_Detail_Edit.this, "사진은 수정 및 삭제를 할수 없습니다.", Toast.LENGTH_SHORT).show();
				
			}
		});
		if(photo_count==0){
			
		}else{
			ly.setVisibility(View.VISIBLE);
			for (int i =0; i<photo_count;i++){
				fl[i].setVisibility(View.VISIBLE);
				imageLoader.displayImage(PublicConstant.HTTP_URL_ALBUMPHOTO+photoList.get(i).Alb_Pho_IMG,iv_img[i],defaultOptions);
			}
		}
	}
	// 이미지 로더 옵션
		void Init() {
			defaultOptions = new DisplayImageOptions.Builder().cacheInMemory(true)
					.cacheOnDisk(true).imageScaleType(ImageScaleType.EXACTLY)
					.considerExifParams(true).bitmapConfig(Bitmap.Config.RGB_565)
					.build();

			ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
					this).threadPriority(Thread.NORM_PRIORITY - 2)
					.denyCacheImageMultipleSizesInMemory()
					.memoryCache(new LruMemoryCache(2 * 1024 * 1024))
					.memoryCacheSize(2 * 1024 * 1024).memoryCacheSizePercentage(20)
					.diskCacheSize(50 * 1024 * 1024).diskCacheFileCount(100)
					.diskCacheExtraOptions(480, 320, null)
					.diskCacheFileNameGenerator(new Md5FileNameGenerator())
					.tasksProcessingOrder(QueueProcessingType.LIFO)
					.writeDebugLogs() // Remove for release app
					.build();
			imageLoader = ImageLoader.getInstance();
			imageLoader.init(config);
		}
	
	// 네.아니오.선택다이얼로그
		void alertDialog() {
			
			AlertDialog.Builder builder = new AlertDialog.Builder(
					this);
			AlertDialog alert;
			builder.setMessage("수정된 내용을 저장하시겠습니까?")
					.setCancelable(false)
					.setPositiveButton("네", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							startNetwork(1);
						}
					})
					.setNegativeButton("아니오",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.cancel();
								}
							});
			alert = builder.create();
			alert.show();
		}
		
		private final BroadcastReceiver mToastMessageReceiver = new BroadcastReceiver() {
			public void onReceive(Context context, Intent intent) {
				LinearLayout layout = (LinearLayout)getLayoutInflater().inflate(R.layout.toast_layout, null);
				TextView toast_tv = (TextView)layout.findViewById(R.id.TOAST_LAYOUT_TV);
				Toast toast = new Toast(Album_Detail_Edit.this);
				toast.setView(layout);
				toast_tv.setText(intent.getStringExtra("PUSH_NAME")+" : "+intent.getStringExtra("PUSH_SUB"));
				toast.setDuration(Toast.LENGTH_LONG);
				toast.show();
			}
		};

}
